import { createApp } from 'vue'
import ElementPlus from 'element-plus'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import App from './App.vue'
import pinia from "@/store";
import router from '@/router'
import '@/assets/styles/global.scss';

/* fontawesome引入操作  */
import 'virtual:svg-icons-register'
/* import the fontawesome core */
import { library } from '@fortawesome/fontawesome-svg-core'
/* import font awesome icon component */
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'
/*  引入指定icon */
// import { faUserSecret } from '@fortawesome/free-solid-svg-icons'
//引入全部icon
import { fas } from '@fortawesome/free-solid-svg-icons'
/* 注册icon到库中 */
library.add(fas)

const app = createApp(App)

/* register FontAwesomeIcon component */
app.component('font-awesome-icon', FontAwesomeIcon)
app.use(pinia)
app.use(ElementPlus, {
    locale: zhCn
})
app.use(router)

/**
 * 全局注册element plus 的icon
 */
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}
app.mount("#app")

/**
 * 自定义命令之v-focus: 焦点事件
 */
app.directive('focus', {
    mounted(el) {
        el.focus();
    }
});

let debounce = (fn, delayParam) => {
    let delay = delayParam || 100;
    let timer;
    return function() {
        let th = this;
        let args = arguments;
        if (timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(function() {
            timer = null;
            fn.apply(th, args);
        }, delay);
    };
}

/**
 * 自定义命令之v-enterNumber: 只能允许输入数字
 */
app.directive('enterNumber', {
    mounted(el, { value = 100 }, vnode) {
        el = el.nodeName === "INPUT" ? el : el.children[0]
        let RegStr = value === 0 ? `^[\\+\\-]?\\d+\\d{0,0}` : `^[\\+\\-]?\\d+\\.?\\d{0,${value}}`;
        el.addEventListener('input', debounce(() => {
            el.value = el.value.match(new RegExp(RegStr, 'g'));
            el.dispatchEvent(new Event('input'))
        }));
    }
});
